package nl.liacs.mms.dn.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.liacs.mms.dn.entities.DigitalNote;

import com.google.appengine.api.datastore.Entity;

@SuppressWarnings("serial")
public class DigitalNotesServlet extends HttpServlet {
	
	private DigitalNotesService notesService = new DigitalNotesService();
	/**
	 * this function returns an XML with the information of one Digital Note
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		// set hostname in service
		notesService.setHostname(getHostname(req));
		
		List<DigitalNote> notes;
		
		String lngString = req.getParameter("lng");
		String latString = req.getParameter("lat");
		if(lngString != null && latString != null){
			double lng = Double.parseDouble(req.getParameter("lng"));
			double lat = Double.parseDouble(req.getParameter("lat"));
			notes = notesService.getNotesNearby(lng,lat);
			notesService.addDistancesAndCardinalDirections(notes,lng,lat);
		}else{
			notes = notesService.getAllNotes();
		}
		
		resp.setContentType("application/xml");
		resp.getWriter().println(notesService.DigitalNotesToXML(notes));
	}
	
	private String getHostname(HttpServletRequest req){
		return "http://" + req.getServerName() + ":" + req.getServerPort();
	}
}
